package com.nostop.common;

import com.nostop.exception.ParamException;
import com.nostop.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {



    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        String url = request.getRequestURL().toString();
        ModelAndView mv;
        String defaulMsg = "系统异常";
        //定义两种规格:请求数据都是用.json结尾 请求页面都使用.page结尾
        if(url.endsWith(".json")){
            if(ex instanceof PermissionException ){
                log.error("未知的 .json异常 url:"+url,ex);
                JsonData result = JsonData.fail(ex.getMessage());
                //这里让JsonData建立一个toMap方法主要是为了配合ModelAndView的这个构造方法的要求
                //这里的jsonView和spring-servlet.xml里面定义的jsonView对齐
                mv = new ModelAndView("jsonView",result.toMap());
            }else if (ex instanceof ParamException) {
                log.error("未知的 .json异常 url:"+url,ex);
                JsonData result = JsonData.fail(ex.getMessage());
                mv = new ModelAndView("jsonView",result.toMap());
            } else {
                JsonData result = JsonData.fail(ex.getMessage());
                log.error("未知的 .json异常 url:"+url,ex);
                mv = new ModelAndView("jsonView",result.toMap());
            }
        }else if(url.endsWith(".page")){
                log.error("未知的 .page异常 url:"+url,ex);
                JsonData jsonData = JsonData.fail(ex.getMessage());
                mv = new ModelAndView("exception",jsonData.toMap());
        }else {
            JsonData jsonData = JsonData.fail(ex.getMessage());
            log.error("未知的 .json异常 url:"+url,ex);
            mv = new ModelAndView("jsonView",jsonData.toMap());
        }
        return mv;
    }

}
